<template>
  <!--网络行为-->
    <search-table
      :columns="listCol" 
      :data="retData.list"
      :total="retData.total"
      :page="queryParams.pageIndex"
      :size.sync="queryParams.pageSize"
      @change-page="getNetBehaviorsList"
      @change-size="getTargetSize"
    >
      <template slot="select-group">
        <Select filterable
          v-model="queryParams.destGroupId"
          placeholder="请选择团队"
          clearable
          transfer
          @on-change="getNetBehaviorsList(1)"
        >
          <Option
            v-for="item in teamList"
            :value="item.id"
            :key="item.id"
            :title="item.name"
            >{{ item.name }}</Option
          >
        </Select>
        <!-- 系统一般不指定实验员 -->
        <!-- <Select filterable
          v-model="queryParams.member"
          placeholder="请选择实验员"
          filterable
          clearable
          transfer
          @on-change="getNetBehaviorsList(1)"
        >
          <Option
            v-for="item in teamList"
            :value="item.id"
            :key="item.id"
            :title="item.name"
          >
            {{ item.name }}
          </Option>
        </Select> -->
        <Select filterable
          v-model.trim="queryParams.appName"
          placeholder="选择协议"
          clearable
          transfer
          filterable
          style="width: 150px"
          @on-change="getNetBehaviorsList(1)"
        >
          <Option
            v-for="(item, index) in appProtocolsList"
            :value="item"
            :key="index"
            >{{ item == 'file_restore_info' ? '文件':item.toUpperCase() }}</Option
          >
        </Select>
        <Input
          v-model.trim="queryParams.srcIpv4"
          placeholder="源IP"
          clearable
          @on-change="getNetBehaviorsList(1)"
        ></Input>
        <Input
          v-model.trim="queryParams.destIpv4"
          placeholder="目标IP"
          clearable
          @on-change="getNetBehaviorsList(1)"
        ></Input>
        <div
          style="display: flex; align-items: center; width: 200px"
          v-if="showMonitoring"
        >
          <span>是否开启网络行为监控：</span>
          <i-switch
            v-model="monitoringtor"
            size="large"
            @on-change="changeNetControl"
          >
            <span slot="open">开启</span>
            <span slot="close">关闭</span>
          </i-switch>
        </div>
      </template>
    
    <!-- <card-list slot="table" :columns="listCol" :data="retData.list"></card-list> -->
    <!-- <Table slot="table" :columns="listCol" :data="retData.list"></Table> -->
    <trafficRetrieval
      v-if="!showTrafficRetrieval"
      :networkBeParams="networkBeParams"
    ></trafficRetrieval>

    <Modal
      v-model="otherInfo"
      title="其他信息"
      width="800"
      :mask-closable="false"
      footer-hide
      @on-visible-change="change"
    >
      <div
        id="threatDetail"
        v-if="protocolType == 'http' || protocolType == 'HTTP'"
      >
        <p>
          <span class="label">URL</span><span>{{ otherDetailsData.uri }}</span>
        </p>
        <p>
          <span class="label">主机</span
          ><span>{{ otherDetailsData.host }}</span>
        </p>
        <p>
          <span class="label">请求方法</span
          ><span>{{ otherDetailsData.method }}</span>
        </p>
        <p>
          <span class="label">请求头</span
          ><span>{{ otherDetailsData.request_header }}</span>
        </p>
        <p>
          <span class="label"> X-forword-for</span
          ><span>{{ otherDetailsData.xff }}</span>
        </p>
        <p>
          <span class="label">请求体</span
          ><span>{{ otherDetailsData.request_body }}</span>
        </p>
        <p>
          <span class="label">状态</span
          ><span>{{ otherDetailsData.status }}</span>
        </p>
        <p>
          <span class="label">响应头</span
          ><span>{{ otherDetailsData.response_header }}</span>
        </p>
        <p>
          <span class="label">响应体</span
          ><span>{{ otherDetailsData.response_body }}</span>
        </p>
      </div>
      <div
        id="threatDetail"
        v-if="protocolType == 'dns' || protocolType == 'DNS'"
      >
        <p>
          <span class="label">域名</span
          ><span>{{ otherDetailsData.domain }}</span>
        </p>
        <p>
          <span class="label">域名解析地址</span
          ><span>{{
            otherDetailsData.domain_ipv4 || otherDetailsData.domain_ipv6
          }}</span>
        </p>
      </div>
      <div
        id="threatDetail"
        v-if="protocolType == 'ftp' || protocolType == 'FTP'"
      >
        <p>
          <span class="label"> 操作指令</span
          ><span>{{ otherDetailsData.cmd }}</span>
        </p>
        <p>
          <span class="label">操作结果</span
          ><span>{{ otherDetailsData.reply }}</span>
        </p>
        <p v-if="otherDetailsData.filename">
          <span class="label">文件名</span
          ><span>{{ otherDetailsData.filename }}</span>
        </p>
      </div>
      <div
        id="threatDetail"
        v-if="protocolType == 'mail' || protocolType == 'MAIL'"
      >
        <p>
          <span class="label">邮件主题</span
          ><span>{{ otherDetailsData.subject }}</span>
        </p>
        <p>
          <span class="label">发件人</span
          ><span>{{ otherDetailsData.from }}</span>
        </p>
        <p>
          <span class="label">收件人</span
          ><span>{{ otherDetailsData.to }}</span>
        </p>
      </div>
      <div
        id="threatDetail"
        v-if="protocolType == 'tds' || protocolType == 'TDS'"
      >
        <p>
          <span class="label"> sql命令</span
          ><span>{{ otherDetailsData.cmd }}</span>
        </p>
        <p>
          <span class="label">错误信息</span
          ><span>{{ otherDetailsData.error }}</span>
        </p>
        <p>
          <span class="label">响应时间</span
          ><span>{{ otherDetailsData.delaytime }}</span>
        </p>
      </div>
      <div
        id="threatDetail"
        v-if="protocolType == 'stun' || protocolType == 'STUN'"
      >
        <p>
          <span class="label">消息类型</span
          ><span>{{ otherDetailsData.type_class }}</span>
        </p>
        <p>
          <span class="label">方法</span
          ><span>{{ otherDetailsData.type_method }}</span>
        </p>
        <p>
          <span class="label">属性及对应值</span
          ><span>{{ otherDetailsData.attribute }}</span>
        </p>
      </div>
      <div
        id="threatDetail"
        v-if="protocolType == 'telnet' || protocolType == 'TEINET'"
      >
        <p>
          <span class="label">操作命令</span
          ><span>{{ otherDetailsData.cmd }}</span>
        </p>
        <p>
          <span class="label">操作结果</span
          ><span>{{ otherDetailsData.reply }}</span>
        </p>
      </div>
      <div
        id="threatDetail"
        v-if="protocolType == 'ssl' || protocolType == 'SSL'"
      >
        <p>
          <span class="label">服务器名称</span
          ><span>{{ otherDetailsData.server_name }}</span>
        </p>
        <p>
          <span class="label">证书发布者</span
          ><span>{{ otherDetailsData.issuer }}</span>
        </p>
        <p>
          <span class="label">证书有效期</span
          ><span>{{ otherDetailsData.validity }}</span>
        </p>
      </div>
      <div
        id="threatDetail"
        v-if="protocolType == 'ssh' || protocolType == 'SSH'"
      >
        <p>
          <span class="label">客户端软件</span
          ><span>{{ otherDetailsData.client_software }}</span>
        </p>
        <p>
          <span class="label">服务器版本</span
          ><span>{{ otherDetailsData.server_version }}</span>
        </p>
        <p>
          <span class="label">服务器软件</span
          ><span>{{ otherDetailsData.server_software }}</span>
        </p>
      </div>
      <div
        id="threatDetail"
        v-if="protocolType == 'mysql' || protocolType == 'MYSQL'"
      >
        <p>
          <span class="label">sql命令</span
          ><span>{{ otherDetailsData.cmd }}</span>
        </p>
        <p>
          <span class="label">错误信息</span
          ><span>{{ otherDetailsData.error }}</span>
        </p>
        <p>
          <span class="label">响应时间</span
          ><span>{{ otherDetailsData.delaytime }}</span>
        </p>
      </div>
      <div
        id="threatDetail"
        v-if="protocolType == 'PostgreSQL' || protocolType == 'POSTGRESQL'"
      >
        <p>
          <span class="label">sql命令</span
          ><span>{{ otherDetailsData.connect_data }}</span>
        </p>
        <p>
          <span class="label">结果</span
          ><span>{{ otherDetailsData.connect_result }}</span>
        </p>
        <p>
          <span class="label">响应时间</span
          ><span>{{ otherDetailsData.delaytime }}</span>
        </p>
      </div>
      <div
        id="threatDetail"
        v-if="protocolType == '文件' || protocolType == 'file'"
      >
        <p>
          <span class="label">文件名称</span
          ><span>{{ otherDetailsData.name }}</span>
        </p>
        <p>
          <span class="label">应用层协议</span
          ><span>{{ otherDetailsData.l7_protocol }}</span>
        </p>
        <p>
          <span class="label">文件大小</span
          ><span>{{ otherDetailsData.size }}</span>
        </p>
        <p>
          <span class="label">文件格式</span
          ><span>{{ otherDetailsData.magic }}</span>
        </p>
        <p>
          <span class="label">md5</span><span>{{ otherDetailsData.md5 }}</span>
        </p>
        <p>
          <span class="label">sha1</span
          ><span>{{ otherDetailsData.sha1 }}</span>
        </p>
        <p>
          <span class="label">sha256</span
          ><span>{{ otherDetailsData.sha256 }}</span>
        </p>
      </div>
      <div
        id="threatDetail"
        v-if="protocolType == 'tftp' || protocolType == 'TFTP'"
      >
        <p>
          <span class="label">文件名称</span
          ><span>{{ otherDetailsData.filename }}</span>
        </p>
        <p>
          <span class="label">文件操作</span
          ><span>{{ otherDetailsData.file_option }}</span>
        </p>
        <p>
          <span class="label">传输模式</span
          ><span>{{ otherDetailsData.transfer_mode }}</span>
        </p>
        <p>
          <span class="label">错误信息</span
          ><span>{{ otherDetailsData.error }}</span>
        </p>
      </div>
      <div v-if="!showType.includes(protocolType)">暂不支持查看该协议其他详细信息</div>
    </Modal>
    </Modal>
  </search-table>
</template>
<script>
import {netBehaviorsList,openNetControl,queryNetControl,appProtocols,fileRestore,fullFlowDown} from '@/api/integration3d';
import { downloadFile } from '@/api/compitionStatic';
import groupMixin from '@/mixin/groupMixin';
import LevelMixin from '@/mixin/levelMixin';
import SearchTable from '@/components/SearchTable/SearchTable';
import { debounce } from '@/libs/utils';
import trafficRetrieval from '@/view/drill_compete/page/componentHW/trafficRetrieval'
export default {
  name: 'networkBehavior',
  // props: ['sceneId', 'poll', 'showMonitoring'],
  props:{
    sceneId:{
      type:String,
      default:()=>''
    },
    poll:{
      type:Boolean,
      default:()=> true
    },
    showMonitoring:{
      type:Boolean,
      default:()=> true
    },
    showTrafficRetrievalBtn:{
      type:Boolean,
      default:()=> true
    }
  },
  mixins: [groupMixin, LevelMixin],
  components: {
    SearchTable,
    trafficRetrieval
  },
  data () {
    return {
      value:'',
      showTrafficRetrieval:true, // 切换流量检索
      monitoringtor: false,
      queryParams: {
        destGroupId: '', //源用户组id
        appName: '',
        srcIpv4: '',
        destIpv4: '',
        pageIndex: 1,
        pageSize: 10
      },
      retData: {
        total: 0,
        list: []
      },

      listCol: [
        {
          title: '开始时间',
          key: 'startTime',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          placement: 'top-left',
          // order: 1,
          minWidth: 140,
        },
        {
          title: '结束时间',
          key: 'endTime',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          minWidth: 140,
          placement: 'top-left'
        },
        {
          title: '源IP',
          key: 'srcIpv4',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          minWidth: 100
        },
        {
          title: '源端口',
          key: 'srcPort',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          minWidth: 100
        },
        {
          title: '目的IP',
          key: 'destIpv4',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          minWidth: 140
        },
        {
          title: '目的端口',
          key: 'destPort',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          minWidth: 100
        },
        {
          title: '应用协议',
          key: 'appName',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          minWidth: 100,
          render: (h,params) => {
            let appName = params.row.appName == 'file_restore_info' ? '文件' : params.row.appName.toUpperCase()
            return h('span', appName)
          }
        },
        {
          title: '其他信息',
          key: 'attackTypeName',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          minWidth: 100,
          render: (h, params) => {
            return h('Button', {
              props: {
                type: 'primary',
                size: 'small',
                ghost:true,
              },
              style: {
                // marginRight: '5px',
              },
              on: {
                click: () => {
                  this.otherDetails(params.row)
                }
              }
            }, '详细信息')
          }
        },
        // {
        //   title: '防守类型',
        //   key: 'defenseTypeName',
        //   width: 100,
        //   tooltip: true
        // },
        // {
        //   title: '状态', //1提交，2审批通过，3审批不通过
        //   key: 'status',
        //   align: 'center',
        //   ellipsis: true,
        //   tooltip: true,
        //   placement: 'top-right',
        //   render: (h, params) => {
        //     return h(
        //       'span',
        //       params.row.status == 1 ? '提交' : params.row.status == 2 ? '审批通过' : '审批不通过'
        //     );
        //   }
        // },
        {
          title: '实验员',
          key: 'srcUserName',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          minWidth: 120,
          render: (h, params) => {
            let srcUserName = params.row.srcUserName || params.row.destUserName ||'无'
            return h('span',srcUserName)
          }

        },
        {
          title: '团队',
          key: 'srcGroupName',
          align: 'center',
          ellipsis: true,
          tooltip: true,
          minWidth: 120,
          render: (h, params) => {
            let srcGroupName = params.row.srcGroupName || params.row.destGroupName || '无'
            return h('span', srcGroupName)
          }
        },
        {
          title: '操作',
          align: 'center',
          // placement: 'top-right',
          key:'action',
          action: true,
          minWidth: 140,
          opList:[
            {
              txt:'流量检索',
              show:()=>{
                return this.showTrafficRetrievalBtn
              },
              on: {
                click: (data) => {
                  this.propsParams(data)
                }
              }
            },
            {
              txt:'文件下载',
              on: {
                click: (data) => {
                  this.fileRestore(data)
                }
              },
              disabled: (data) => {
                let {appName,id} = data
                let fileType = ['文件','文件传输','file']
                return !fileType.includes(appName)
              }
            }
          ],
          // render: (h, params) => {
          //   let {appName,id} = params.row
          //   let fileType = ['文件','文件传输','file']
          //   return h('div', {
          //     style: {
          //       display: 'flex',
          //       'justify-content': 'space-evenly'
          //     }
          //   }, [
          //     h('Button', {
          //       props: {
          //         type: 'primary',
          //         size: 'small',
          //         ghost: true,
          //         disabled: true
          //       },
          //       style: {
          //         marginRight: '5px',
          //         display: 'none'
          //       },
          //       on: {
          //         click: () => {
          //           this.propsParams(params.row)
          //         }
          //       }
          //     }, '流量检索'),
          //     h('Button', {
          //       props: {
          //         type: 'primary',
          //         size: 'small',
          //         ghost: true,
          //         disabled: !fileType.includes(appName)
          //       },
          //       style: {
          //         // marginRight: '5px',
          //         // display: fileType.includes(appName) ? 'block' : 'none'
          //       },
          //       on: {
          //         click: () => {
          //           this.fileRestore(params.row)
          //         }
          //       }
          //     }, '文件下载'),
          //   ])
          // },
        }
      ],
      // 记录传参流量检索
      networkBeParams: {},

      // 其他信息展示
      otherInfo: false,
      otherDetailsData: {},
      protocolType: '',
      // 获取协议
      appProtocolsList:[],
      showType:['http','HTTP','dns','DNS','ftp','FTP','mail','MAIL','tds','TDS','stun','STUN','telnet','TEINET',,'ssl','SSL','ssh','SSH','mysql','MYSQL','PostgreSQL','POSTGRESQL','tftp','TFTP','file','文件']
    };
  },
  computed: {
    filterTeamList () {
      return this.teamList.filter((item) => item.name !== '目标方管理员组');
    }
  },

  watch: {},
  created () { },
  beforeDestroy () { },
  async mounted () {
    await this.queryNetControl();
    await this.appProtocols();
    await this.getNetBehaviorsList();
  },
  methods: {
    getTargetSize(val) {
      this.queryParams.pageSize = val
      this.getNetBehaviorsList(1)
    },
    change (val) {
      this.otherInfo = val
    },
    // 流量检索
    propsParams (row) {
      // this.networkBeParams = row
      // this.showTrafficRetrieval = true
      row.showFlag = true
      this.$emit('toTrafficRetrieval', row)
    },

    // 获取列表数据
    getNetBehaviorsList: debounce(function (val) {
      if (val) {
        this.queryParams.pageIndex = val
      }
      let params = {
        pageIndex: this.queryParams.pageIndex,
        pageSize: this.queryParams.pageSize,
        appName: this.queryParams.appName,
        srcIpv4: this.queryParams.srcIpv4,
        destIpv4: this.queryParams.destIpv4,
        destGroupId: this.queryParams.destGroupId,
        srcGroupId: this.queryParams.destGroupId,
        projectId: this.$route.query.prjid,
        // projectId: 'Jf9bb58b53934df183b83878f74316e6'
      }
      netBehaviorsList(params).then(res => {
        if (res.code == 1) {
          this.retData.list = res.data.items
          this.retData.total = res.data.total
        } else {
          this.retData.list = []
          this.retData.total = 0
        }
      }).catch(error => {
        this.$Message.error(error)
      })
    }, 500),

    queryNetControl () {
      let params = {
        projectId: this.$route.query.prjid,
        // projectId: 'J6c710a699fd4d83a7418c468bf5b562',
      }
      queryNetControl(params).then(res => {
        console.log('============', res);
        if (res.code == 1) {
          this.monitoringtor = res.data
          console.log(' this.monitoringtor:', this.monitoringtor)
        } else {
          this.$Message.warning(res.message)
        }
      }).catch(error => {
        this.$Message.error(error)
      })
    },
    changeNetControl (val) {
      let params = {
        projectId: this.$route.query.prjid,
        // projectId: 'J6c710a699fd4d83a7418c468bf5b562',
        enable: val
      }
      openNetControl(params).then(res => {
        if (res.code == 1) {
          this.monitoringtor = res.data
          this.$Message.success('操作成功')
          // this.queryNetControl() // 查状态感觉有点不对 获取的永远为true
        } else {
          this.$Message.warning(res.message)
        }
      }).catch(error => {
        this.$Message.error(error)
      })
    },

    // 其他信息
    otherDetails (row) {
      console.log(' otherDetails ~ row.extra:', row.extra)
      this.otherDetailsData = row.extra
      this.protocolType = row.appName
      this.otherInfo = true
      console.log('🚀this.otherInfo:', this.otherInfo, this.protocolType)
    },

    appProtocols () {
      appProtocols().then(res => {
        if (res.code == 1) {
          console.log('==', res.data);
          this.appProtocolsList = res.data
        } else {
          this.appProtocolsList = []
          this.$Message.warning(res.message)
        }
      }).catch(error => {
        this.$Message.error(error)
      })
    },

    // 下载传输文件
    fileRestore (row) {
      fileRestore(row.id).then(res => {
        // 返回的文件流类型对不上 res.type == 'application/octet-stream' 直接惯例判断res.code 
        if (!res.code) {
            let type = row.extra.magic
            const downloadElement = document.createElement('a');
            const href = window.URL.createObjectURL(res);
            downloadElement.href = href;
            downloadElement.download = `网络行为.${type}`;
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement); // 下载完成移除元素
            window.URL.revokeObjectURL(href); // 释放掉blob对象
          } else {
            this.$Message.error('下载文件失败!不存在文件数据！');
          }
        }).catch(error => {
          console.log(error)
        });
    }
  }
};
</script>

<style>
.drillsTable .ivu-poptip-body {
  text-align: left !important;
}
.scenesHeader {
  margin-bottom: 16px;
}
.drillTables {
  min-height: 300px;
}
.drillsTable.ivu-table-wrapper {
  overflow: inherit;
}
</style>
<style scoped>
.Titles {
  background: #eeeeee;
  margin: 16px auto;
  padding: 10px 0;
}
.targetHeader {
  padding: 10px;
  margin-bottom: 10px;
}
#threatDetail {
  display: table;
  width: 100%;
  border: 1px solid #eee;
  table-layout: fixed;
  word-break: break-all;
}
#threatDetail p {
  display: table-row;
  line-height: 36px;
  text-align: center;
}
#threatDetail p span {
  display: table-cell;
  border-bottom: 1px solid #eee;
}
</style>
